﻿using System.Collections.Specialized;
using System.Data;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using Org.EasyWeb.DataAccess;
using Org.EasyWeb.Exception;
using Org.EasyWeb.Sys;
using Org.EasyWeb.SysUtil;
using Org.EasyWeb.Xml;

namespace Org.EasyWeb.Data
{
    public abstract class WebSimpleUpdateXmlDataSet : WebSimpleUpdateDataSet, INonUIResolvers, IDoubleTransform
    {
        // Fields
        private string fDataXml;
        private XPathNavigator fDataXmlDocument;
        private string fIeXsltFile;
        private TableResolver fMainResolver;
        private TableResolverCollection fNonUIResolvers;
        private bool fQueryStringInput;
        private PageStyle fStyle = PageStyle.Insert;

        // Methods
        protected WebSimpleUpdateXmlDataSet()
        {
            this.fMainResolver = this.GetMainResolver();
            this.fDataXml = this.GetDataXml();
            this.fQueryStringInput = true;
        }

        protected void CommitData()
        {
            base.UpdateTableresolvers(this.MainResolver, this.fNonUIResolvers);
        }

        protected override void FillCustomTables(bool isPost, string operation, NameValueCollection queryString, DataSet postDataSet)
        {
            if (this.DataXml != "")
            {
                this.SetDataXmlDocument();
            }
            switch (this.fStyle)
            {
                case PageStyle.Insert:
                    if (!isPost)
                    {
                        this.MainResolver.CreateVirtualTable();
                        this.MainResolver.GetNewRow();
                        this.MainResolver.AddVirtualFields();
                        this.MainResolver.GetConstraints(UpdateKind.Insert);
                        break;
                    }
                    this.MainResolver.SelectTableStructure();
                    this.MainResolver.SetCommands(AdapterCommand.Insert);
                    break;

                case PageStyle.Update:
                    if (isPost)
                    {
                        ResolverUtil.SetOldKeyValues(this.MainResolver, postDataSet);
                        if (this.MainResolver.HostTable.Rows.Count == 0)
                        {
                            throw new NoRecordException();
                        }
                        this.MainResolver.SetCommands(AdapterCommand.Update);
                        return;
                    }
                    ResolverUtil.SetKeyValues(this.MainResolver, queryString, queryString["ID"]);
                    this.MainResolver.AddVirtualFields();
                    this.MainResolver.GetConstraints(UpdateKind.Update);
                    return;

                case PageStyle.Delete:
                    return;

                case PageStyle.Detail:
                    ResolverUtil.SetKeyValues(this.MainResolver, queryString, queryString["ID"]);
                    this.MainResolver.AddVirtualFields();
                    return;

                default:
                    return;
            }
            if (!isPost)
            {
                ResolverUtil.SetDefaultValues(this.MainResolver, queryString);
            }
            if (!isPost)
            {
                foreach (DataRow row in this.MainResolver.HostTable.Rows)
                {
                    this.MainResolver.SetDefaultValue(row);
                }
            }
        }

        protected virtual string GetDataXml()
        {
            return "";
        }

        protected virtual string GetDataXslt(PageStyle style)
        {
            return DataSetOperUtil.GetDataXslt(style, "");
        }

        public override string GetDefaultPage(bool isPost, PageStyle style, string operation, PageX pageX, string retURL)
        {
            if (retURL != "")
            {
                return retURL;
            }
            return "";
        }

        public virtual string GetDefaultXsltTemplate(PageStyle style, string operation)
        {
            return DataSetOperUtil.GetDefaultXsltTemplate(this.fStyle, operation);
        }

        public int GetDocumentNumber(PageStyle style, string operation)
        {
            return 1;
        }

        protected abstract TableResolver GetMainResolver();
        public bool GetSupportDoubleTransform(PageStyle style, string operation)
        {
            return true;
        }

        public XPathNavigator GetXmlDocument(int i, PageStyle style, string operation)
        {
            return this.fDataXmlDocument;
        }

        public sealed override string GetXsltFile(bool isIe, PageStyle style, string operation)
        {
            return this.fIeXsltFile;
        }

        protected void HandleInformationException(NameValueCollection queryString, DataSet postDataSet, PageStyle style)
        {
            BaseDataSet hostDataSet = new BaseDataSet
            {
                ConnectionStr = base.ConnectionStr
            };
            using (hostDataSet)
            {
                DataTable hostTable;
                this.MainResolver.SetHostDataSet(hostDataSet);
                bool queryStringInput = this.QueryStringInput;
                this.QueryStringInput = false;
                try
                {
                    base.SetData(false, PageStyle.Custom, string.Empty, queryString);
                    hostTable = this.MainResolver.HostTable;
                    if (hostTable == null)
                    {
                        hostTable = this.MainResolver.SelectTableStructure();
                    }
                }
                finally
                {
                    this.QueryStringInput = queryStringInput;
                    this.MainResolver.HostDataSet = this;
                }
                if (base.Tables.Contains(this.MainResolver.TableName))
                {
                    base.Tables.Remove(this.MainResolver.TableName);
                }
                DataTable table2 = DataSetUtil.CreateStringTable(hostTable);
                base.Tables.Add(table2);
                this.MainResolver.MergeErrorTable(base.Tables[this.MainResolver.TableName], postDataSet.Tables[this.MainResolver.TableName], hostTable);
                DataTable errorTable = this.MainResolver.ErrorObjects.ErrorTable;
                foreach (DataTable table4 in hostDataSet.Tables)
                {
                    if (!base.Tables.Contains(table4.TableName))
                    {
                        base.Tables.Add(table4.Copy());
                    }
                }
                base.Tables.Add(errorTable);
            }
        }

        public override string Post(PageStyle style, string operation, NameValueCollection queryString, DataSet postDataSet)
        {
            base.Post(style, operation, queryString, postDataSet);
            this.PostData(this.fStyle, queryString, postDataSet);
            return null;
        }

        protected void PostData(PageStyle style, NameValueCollection queryString, DataSet postDataSet)
        {
            switch (style)
            {
                case PageStyle.Insert:
                    this.MainResolver.CheckFirstConstraints(UpdateKind.Insert, postDataSet);
                    this.MainResolver.Insert(postDataSet);
                    break;

                case PageStyle.Update:
                    this.MainResolver.CheckFirstConstraints(UpdateKind.Update, postDataSet);
                    this.MainResolver.Update(postDataSet);
                    break;
            }
            try
            {
                bool flag = false;
                try
                {
                    this.MainResolver.CheckConstraints(postDataSet);
                    this.MainResolver.CheckError();
                }
                catch (InformationException)
                {
                    flag = true;
                }
                if (flag)
                {
                    throw new InformationException();
                }
            }
            catch (InformationException exception)
            {
                this.HandleInformationException(queryString, postDataSet, style);
                throw exception;
            }
            this.CommitData();
        }

        private void SetDataXmlDocument()
        {
            string dataXslt = this.GetDataXslt(this.fStyle);
            if (dataXslt != string.Empty)
            {
                string xslFile = FileUtil.ParseFileName(AppSettings.Current.XmlPath + dataXslt);
                XmlDocument xml = new XmlDocument();
                string s = string.Format("<?xml version=\"1.0\" encoding=\"gb2312\"?><Toolkit version=\"2.0\" xmlns:tk=\"http://www.qdocuments.net\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><tk:Module><tk:Title></tk:Title><tk:DataSet></tk:DataSet><tk:Resolvers><tk:Resolver Style=\"Normal\" Main=\"true\" Order=\"10\"><tk:RegName>{0}</tk:RegName><tk:Xml>Data/{1}</tk:Xml></tk:Resolver></tk:Resolvers></tk:Module></Toolkit>", this.MainResolver.CustomAttribute.RegName, this.DataXml);
                xml.Load(new XmlTextReader(AppSettings.Current.XmlPath, new StringReader(s)));
                string content = XslTransformUtil.Transform(xml, xslFile, TransformSetting.All);
                if (AppSettings.Current.Debug)
                {
                    FileUtil.SaveFile(AppSettings.Current.XmlPath + "Temp.xml", content, Encoding.UTF8);
                }
                this.fDataXmlDocument = new XPathDocument(new StringReader(content)).CreateNavigator();
            }
        }

        // Properties
        public string DataXml
        {
            get
            {
                if ((this.fDataXml == "") && (this.MainResolver is Xml2TableResolver))
                {
                    return (this.MainResolver as Xml2TableResolver).XmlFile;
                }
                return this.fDataXml;
            }
        }

        public string IeXsltFile
        {
            get
            {
                return this.fIeXsltFile;
            }
            set
            {
                this.fIeXsltFile = value;
            }
        }

        public TableResolver MainResolver
        {
            get
            {
                return this.fMainResolver;
            }
        }

        public TableResolverCollection NonUIResolvers
        {
            get
            {
                if (this.fNonUIResolvers == null)
                {
                    this.fNonUIResolvers = new TableResolverCollection();
                }
                return this.fNonUIResolvers;
            }
        }

        protected bool QueryStringInput
        {
            get
            {
                return this.fQueryStringInput;
            }
            set
            {
                this.fQueryStringInput = value;
            }
        }

        public PageStyle Style
        {
            get
            {
                return this.fStyle;
            }
            set
            {
                this.fStyle = value;
            }
        }
    }
}
